package com.vooda.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.vooda.constant.ErrorCode;
import com.vooda.dao.UserDao;
import com.vooda.dto.bo.UserBo;
import com.vooda.dto.vo.BaseResult;
import com.vooda.dto.vo.UserVo;
import com.vooda.entity.User;
import com.vooda.service.AuthService;
import com.vooda.service.UserService;
import com.vooda.util.AES;
import com.vooda.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.transaction.Transactional;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author KennyDavid
 */

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private AuthService authService;
    private RedisTemplate<String, String> redisTemplate;

    public UserServiceImpl(UserDao userDao, AuthService authService, RedisTemplate<String, String> redisTemplate) {
        this.userDao = userDao;
        this.authService = authService;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public BaseResult<UserVo> login(UserBo userBo) {

        //todo 根据code获取openid
        Map<String, Object> map = new HashMap<>();
        map.put("appid", "wx5e4c274192295c35");
        map.put("secret", "50704061ad5ac28db065eb810b74461b");
        map.put("js_code", userBo.getCode());
        map.put("grant_type", "authorization_code");
        String responses = HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", map);
        JSONObject jsonObject = JSON.parseObject(responses);
        String openid = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        redisTemplate.opsForValue().set("session_key", session_key);

        //todo 存储用户信息 根据userId生成token返回给前端
      /*  log.info(responses);
        log.info(openid);
        log.info(session_key);*/

        User user;
        if (ObjectUtils.isEmpty(openid)) {
            return new BaseResult<>(ErrorCode.OPEN_ID_ERROR.getCode(), ErrorCode.OPEN_ID_ERROR.getMsg());
        }
        user = userDao.findByOpenIdAndIsDel(openid, false);
        if (ObjectUtils.isEmpty(user)) {
            user = new User();
            BeanUtils.copyProperties(userBo, user);
            user.setIsDel(false);
            user.setOpenId(openid);
            userDao.saveAndFlush(user);
        }

        String token = authService.createToken(user.getId());

        UserVo userVo = new UserVo();
        user.setName(userBo.getName());
        user.setImageUrl(userBo.getImageUrl());
        userDao.saveAndFlush(user);

        BeanUtils.copyProperties(user, userVo);
        userVo.setToken(token);

        return new BaseResult<>(userVo);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public BaseResult beCashier(Long userId) {
        User one = userDao.findOne(userId);
        if (!ObjectUtils.isEmpty(one)) {
            one.setIsCashier(true);
        }
        userDao.saveAndFlush(one);
        return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    @Override
    public BaseResult userPhone(Long userId, String iv, String encryptedData) {
        User one = userDao.findOne(userId);
        Map map = new HashMap();
        String session_key = redisTemplate.opsForValue().get("session_key");
        try {
            byte[] resultByte = AES.decrypt(Base64.decodeBase64(encryptedData),
                    Base64.decodeBase64(session_key),
                    Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                String userInfo = new String(resultByte, "UTF-8");
                map.put("status", "1");
                map.put("msg", "解密成功");
                map.put("userInfo", userInfo);
            } else {
                map.put("status", "0");
                map.put("msg", "解密失败");
            }
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        String decodeJSON = gson.toJson(map);
        JSONObject jsonObject = JSON.parseObject(decodeJSON);
        String userInfo = jsonObject.getString("userInfo");
        JSONObject jo = JSON.parseObject(userInfo);
        String phoneNumber = jo.getString("phoneNumber");

        System.out.println(decodeJSON);
        //log.info("---------" + phoneNumber + "---------");
        one.setPhone(phoneNumber);
        userDao.saveAndFlush(one);
        if (ObjectUtils.isEmpty(phoneNumber)) {
            return new BaseResult(ErrorCode.GET_PHONE_ERROR.getCode(), ErrorCode.GET_PHONE_ERROR.getMsg());
        }
        return new BaseResult(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }
}
